/*
 * @Author: xiaoliang
 * @Date: 2025-03-05 16:02:15
 * @LastEditors: xiaoliang
 * @LastEditTime: 2025-03-05 16:05:07
 * @FilePath: /codepiece/$set.js
 * @Description: $set 实现原理
 */

Vue.prototype.$set = function (target, key, val) {
  // 1. 处理数组的情况
  if (Array.isArray(target) && isValidArrayIndex(key)) {
    target.length = Math.max(target.length, key);
    target.splice(key, 1, val);
    return val;
  }

  // 2. 处理对象中已存在的属性
  if (key in target && !(key in Object.prototype)) {
    target[key] = val;
    return val;
  }

  // 3. 处理对象中不存在的属性
  const ob = target.__ob__;
  if (!ob) {
    target[key] = val;
    return val;
  }

  // 4. 将新属性设置为响应式，并通知依赖更新
  defineReactive(ob.value, key, val);
  ob.dep.notify();
  return val;
};